<template>
    <div ref="cardRef" class="forward-card" :class="cardClass" :style="cardTransform">
        <slot />
    </div>
</template>

<script setup lang="ts">
interface Props {
    maxRotation?: number
    sensitivity?: number
    cardClass?: string
    perspective?: number
    translateZ?: number
}

const props = withDefaults(defineProps<Props>(), {
    maxRotation: 40, // 加大最大旋转角度
    sensitivity: 0.1, // 增加灵敏度
    cardClass: '',
    perspective: 1000,
    translateZ: 180
})
const per = ref(props.perspective)

// 3D效果相关状态
const cardRef = ref<HTMLElement | null>(null)
const rotateX = ref(0)
const rotateY = ref(0)

// 计算3D变换样式
const cardTransform = computed(() => {
    return {
        transform: `perspective(${per.value}px) rotateX(${rotateX.value}deg) rotateY(${rotateY.value}deg) translateZ(${props.translateZ}px)`,
        transition: 'transform 0.1s ease-out'
    }
})

// 计算朝向函数
const calculateRotation = (e: MouseEvent) => {
    if (!cardRef.value) return

    const rect = cardRef.value.getBoundingClientRect()
    const centerX = rect.left + rect.width / 2
    const centerY = rect.top + rect.height / 2

    // 计算鼠标相对于卡片中心的位置
    const deltaX = e.clientX - centerX
    const deltaY = e.clientY - centerY

    // 计算旋转角度（限制最大旋转角度）
    const maxRotation = props.maxRotation
    const sensitivity = props.sensitivity

    // Y轴旋转（左右朝向）
    rotateY.value = Math.max(-maxRotation, Math.min(maxRotation, deltaX * sensitivity))

    // X轴旋转（上下朝向）
    rotateX.value = Math.max(-maxRotation, Math.min(maxRotation, -deltaY * sensitivity))
}

// 重置旋转
const resetRotation = () => {
    rotateX.value = 0
    rotateY.value = 0
}

// 监听鼠标位置
onMounted(() => {
    window.addEventListener('mousemove', calculateRotation)
})

onUnmounted(() => {
    window.removeEventListener('mousemove', calculateRotation)
})

// 暴露方法给父组件
defineExpose({
    resetRotation
})
</script>

<style scoped>
.forward-card {
    font-family: "Hanzipen SC", "翩翩体-简", "Marker Felt", "Comic Sans MS",
        "Chalkboard SE", "Bradley Hand", "Brush Script MT", cursive, sans-serif;
    transform-style: preserve-3d;
    backface-visibility: hidden;
    will-change: transform;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    display: inline-block;
}

.forward-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg,
            rgba(255, 255, 255, 0.1) 0%,
            rgba(255, 255, 255, 0.05) 50%,
            rgba(0, 0, 0, 0.05) 100%);
    pointer-events: none;
    z-index: 1;
}

/* 增强3D效果的阴影 */
.forward-card::after {
    content: '';
    position: absolute;
    top: 100%;
    left: 50%;
    width: 80%;
    height: 20px;
    background: radial-gradient(ellipse, rgba(0, 0, 0, 0.1) 0%, transparent 70%);
    transform: translateX(-50%) rotateX(90deg);
    transform-origin: top;
    pointer-events: none;
    z-index: -1;
}
</style>